package com.css.crm.vo;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

import org.apache.log4j.Logger;

/**
 * Virtual object PermissionCollection 
 */
/*
 * Log			Date			Name					Description
 * 0024746	 	2012 DEC 18		lawrence.ng.c.k			Creation
 */
@ManagedBean
@SessionScoped
public class PermissionCollection implements Serializable{
	
	private static final long serialVersionUID = -3128725418497392189L;
	private static final Logger log = Logger.getLogger(PermissionCollection.class);
	private ArrayList<AbstractObjectPermission> permissionList;
	private Hashtable<String, AbstractObjectPermission> permissionTable;

	public PermissionCollection() {
		permissionTable = new Hashtable<String, AbstractObjectPermission>();
	}

	@SuppressWarnings("unchecked")
	public void setPermissionList(List<? extends AbstractObjectPermission> list) {
		this.permissionList = (ArrayList<AbstractObjectPermission>) list;
		updateHashtable();
	}

	/**
	 * Add object permissions into permission hash table
	 */
	/*
	 * Log			Date			Name					Description
	 * 0024746	 	2012 DEC 18		lawrence.ng.c.k			Creation
	 */
	private void updateHashtable() {
		if (permissionTable == null) {
			permissionTable = new Hashtable<String, AbstractObjectPermission>();
		} else {
			permissionTable.clear();
		}
		for (AbstractObjectPermission p : getPermissionList()) {
			permissionTable.put(p.getObjectId(), p);
			log.debug(p.getObjectId() + " --> " + p );
		}
	}

	public ArrayList<AbstractObjectPermission> getPermissionList() {
		return (permissionList == null ? new ArrayList<AbstractObjectPermission>() : permissionList);
	}

	public AbstractObjectPermission getPermission(String objectId) {
		return permissionTable.get(objectId);
	}
	
	/**
	 * Return child list of permission by parent id
	 * 
	 * @param parentId - parent id
	 * @return PermissionCollection
	 */
	/*
	 * Log			Date			Name					Description
	 * 0024746	 	2012 DEC 18		lawrence.ng.c.k			Creation
	 */
	public PermissionCollection getChildList(String parentId){
		
		PermissionCollection childCollection = new PermissionCollection();
		ArrayList<AbstractObjectPermission> childList = new ArrayList<AbstractObjectPermission>();
		
		for (AbstractObjectPermission aop : permissionList){
			if (aop.getParentObjectId()!=null && aop.getParentObjectId().equals(parentId)){
				childList.add(aop);
			}
		}
		
		childCollection.setPermissionList(childList);
		childCollection.updateHashtable();
		
		return childCollection;
	}

}
